package model

import (
	"ReaderInOutLog/logger"
	"ReaderInOutLog/util"
	"fmt"
	"time"

	_ "github.com/denisenkom/go-mssqldb" // SQL Server driver
	"github.com/go-xorm/xorm"
)

var db *xorm.Engine
var err error
var lg, _ = logger.ConfigureLogger()

// ConnectDB initializes the XORM database connection and returns the Engine instance.
func ConnectDB() {

	user := util.DbUser
	password := util.DbPassWord
	host := util.DbHost
	port := util.DbPort
	database := util.DbName

	// var engine *xorm.Engine
	dsn := fmt.Sprintf("sqlserver://%s:%s@%s:%s?database=%s&encrypt=disable", user, password, host, port, database)
	lg.Debugf("dsn: %s", dsn)
	db, err = xorm.NewEngine("mssql", dsn)
	if err != nil {
		fmt.Printf("failed to connect database: %v", err)
		return
	}

	db.ShowSQL(util.IsShowDb)
	fmt.Println("Connected to database")
	// Optional: You can set some global configurations for the engine here.
	// For example, to set the logger:
	// engine.SetLogger(xorm.NewSimpleLogger(os.Stdout))
	db.SetMaxIdleConns(100)
	db.SetMaxOpenConns(100)
	db.SetConnMaxLifetime(10 * time.Second)
}

// CloseDB closes the XORM database connection.
func CloseDB() {
	err := db.Close()
	if err != nil {
		return
	}
}
